package br.com.gip.repository.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.gip.repository.model.Artefato;
import br.com.gip.repository.model.Projeto;
import br.com.gip.repository.persistence.HibernateDao;

@Repository
@Transactional
public class ArtefatoDao extends HibernateDao<Artefato, Long> {

	private static final long serialVersionUID = 1686315177541882870L;

	public Artefato findByNome(String nome) {
		Criteria criteria = this.getCurrentSession().createCriteria(Artefato.class, "a");
		criteria.add(Restrictions.eq("nome", nome));
		return (Artefato) criteria.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<Artefato> findByProjeto(Projeto projeto) {
		Criteria criteria = this.getCurrentSession().createCriteria(Artefato.class, "a");
		criteria.add(Restrictions.eq("projeto.id", projeto.getProjetoId()));
		criteria.addOrder(Order.asc("categoria.id"));
		return (List<Artefato>) criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Artefato> findByFilter(String nome, Long projetoId, Long categoriaId) {
		this.getCurrentSession().clear();

		Criteria criteria = this.getCurrentSession().createCriteria(Artefato.class, "a");
		
		if (!StringUtils.isBlank(nome)) {
			criteria.add(Restrictions.eq("nome", nome));	
		}
		
		if (projetoId != null && projetoId != 0) {
			criteria.add(Restrictions.eq("projeto.id", projetoId));
		}
		
		if (categoriaId != null && categoriaId != 0) {
			criteria.add(Restrictions.eq("categoria.id", categoriaId));
		}
		
		return (List<Artefato>) criteria.list();
	}
	
}